package com.example.myapplication;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.bean.Person;
import com.example.myapplication.bean.User;
import com.example.myapplication.dao.MySQLiteOpenHelper;
import com.example.myapplication.databinding.ActivityMainUpdateBinding;
import com.example.myapplication.service.SharedPreferencesService;

import java.util.Map;
import java.util.Objects;

/**
 * 修改账号和密码界面
 */
public class MainActivityUpdate extends AppCompatActivity {

    private ActivityMainUpdateBinding updateBinding;
    // 修改账号还是密码 ? true修改账号 : false修改密码
    private boolean update;
    // 新账号校验是否通过，true为全部通过，false为不通过
    private boolean newAccountCheck;
    // 新密码校验是否通过，true为全部通过，false为不通过
    private boolean newPasswordCheck;
    // 是否允许提交修改
    private boolean commit;

    private Intent intent;

    private MySQLiteOpenHelper mySQLiteOpenHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_update);

        updateBinding = ActivityMainUpdateBinding.inflate(getLayoutInflater());
        setContentView(updateBinding.getRoot());
        mySQLiteOpenHelper = new MySQLiteOpenHelper(this);

        Map<String, Object> userInfo = SharedPreferencesService.getUserInfo(this);
        String account = (String) userInfo.get("account");
        //String password = (String) userInfo.get("password");
        if (!userInfo.isEmpty() && !Objects.requireNonNull(account).isEmpty()) {
            updateBinding.accountText.setText(account);
        }
        // 默认修改账号为相同账号
        newAccountCheck = true;
        // 默认单选修改密码
        updateBinding.updatePasswordBtn.setChecked(true);
        // 修改账户点击事件处理
        updateBinding.updateAccountBtn.setOnClickListener(view -> {
            newAccountCheck = false;
            updateBinding.accountText.setText("");
            updateBinding.accountTextTip.setText("");
            updateBinding.passwordText.setText("");
            updateBinding.confirmPasswordText.setText("");
            updateBinding.passwordText.setVisibility(View.GONE);    // 默认隐藏密码输入框
            updateBinding.passwordTextTip.setText("");
            updateBinding.confirmPasswordTextTip.setText("");
            update = true;  // 标记为修改账号
        });
        // 修改密码点击事件处理
        updateBinding.updatePasswordBtn.setOnClickListener(view -> {
            updateBinding.accountTextTip.setText("");
            updateBinding.passwordText.setVisibility(View.VISIBLE); // 默认显示密码输入框
            updateBinding.passwordTextTip.setText("");
            update = false; // 标记为修改密码
        });

        // 注销
        if (!userInfo.isEmpty() && !Objects.requireNonNull(account).isEmpty()) {
            Button layoutButton = new Button(this);
            layoutButton.setText("注销账号");
            layoutButton.setBackground(ContextCompat.getDrawable(this, R.drawable.button_1));
            layoutButton.setId(R.id.dl_qhzhh);
            layoutButton.setOnClickListener(view -> {
                LayoutInflater inflater = LayoutInflater.from(this);
                View customView = inflater.inflate(R.layout.pop_up, null);
                TextView title = customView.findViewById(R.id.up_title);
                TextView message = customView.findViewById(R.id.up_tip);
                title.setText("注销提示");
                message.setText("确认注销？ 注销账号后将不复存在");
                // 创建一个弹窗构造器
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setView(customView);
                // 创建并显示弹窗
                AlertDialog dialog = builder.create();
                dialog.show();
                // 弹窗-确认
                TextView sure = customView.findViewById(R.id.up_confirm);
                sure.setOnClickListener(view1 -> {
                    mySQLiteOpenHelper = new MySQLiteOpenHelper(this);
                    Integer userId = (Integer) userInfo.get("userId");
                    boolean delUserSuccess = mySQLiteOpenHelper.deleteUser(userId);
                    Person person = new Person();
                    person.setUserId(userId);
                    boolean delPersonsSuccess = mySQLiteOpenHelper.deletePerson(person);
                    if (delUserSuccess && delPersonsSuccess) {
                        // 删除登录用户信息
                        SharedPreferencesService.deleteUserInfo(this);
                        // 提示删除成功并跳转到登录界面
                        Toast.makeText(this, "账户注销成功", Toast.LENGTH_SHORT).show();
                        intent = new Intent(this, MainActivityLogin.class);
                        startActivity(intent);
                        // 关闭弹窗
                        dialog.cancel();
                        // 结束当前Activity
                        finish();
                    }else {
                        Toast.makeText(this, "账户注销失败", Toast.LENGTH_SHORT).show();
                    }
                });

                // 弹窗-取消
                TextView off = customView.findViewById(R.id.up_cancel);
                off.setOnClickListener(view1 -> {
                    // 关闭弹窗
                    dialog.cancel();
                });
            });
            // 添加按钮
            updateBinding.logOff.addView(layoutButton);
        }

        // 账号文本框
        updateBinding.accountText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!update) {  // 修改密码
                    if (!userInfo.get("account").equals(updateBinding.accountText.getText().toString().trim())) {
                        updateBinding.accountTextTip.setTextColor(ContextCompat.getColor(MainActivityUpdate.this, R.color.red));
                        updateBinding.accountTextTip.setText("账号需一致");
                        newAccountCheck = false;  // 标记新账号校验不通过
                    } else {
                        updateBinding.accountTextTip.setText("");
                        newAccountCheck = true;   // 标记新账号校验通过
                    }
                } else {    // 修改账号
                    if (userInfo.get("account").equals(updateBinding.accountText.getText().toString().trim())) {
                        updateBinding.accountTextTip.setTextColor(ContextCompat.getColor(MainActivityUpdate.this, R.color.red));
                        updateBinding.accountTextTip.setText("新账号与旧账号相同");
                        newAccountCheck = false;  // 标记新账号校验不通过
                    } else {
                        updateBinding.accountTextTip.setText("");
                        newAccountCheck = true;   // 标记新账号校验通过
                    }
                }
            }
        });

        // 新密码文本框输入后监听
        updateBinding.passwordText.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!update) {  // 修改密码
                    String newPassword = updateBinding.passwordText.getText().toString().trim();
                    newPasswordCheck = false;
                    // 判断新密码是否为空
                    if (newPassword.isEmpty()) {
                        // 新密码为空
                        updateBinding.passwordTextTip.setTextColor(ContextCompat.getColor(MainActivityUpdate.this, R.color.red));
                        updateBinding.passwordTextTip.setText("新密码不能为空");
                        // 如果新密码为空，提示后隐藏确认密码输入框
                        updateBinding.confirmPasswordText.setEnabled(false);
                        updateBinding.confirmPasswordText.setVisibility(View.GONE);
                        return;
                    }
                    if (newPassword.equals(userInfo.get("password"))) {
                        updateBinding.passwordTextTip.setTextColor(ContextCompat.getColor(MainActivityUpdate.this, R.color.red));
                        updateBinding.passwordTextTip.setText("与原密码相同");
                        // 如果新密码与原密码相同，提示后隐藏确认密码输入框
                        updateBinding.confirmPasswordText.setEnabled(false);
                        updateBinding.confirmPasswordText.setVisibility(View.GONE);
                    } else if (newPassword.length() < 6) {
                        updateBinding.passwordTextTip.setTextColor(ContextCompat.getColor(MainActivityUpdate.this, R.color.red));
                        updateBinding.passwordTextTip.setText("长度不能少于6位");
                        // 如果新密码长度少于6位，提示后隐藏确认密码输入框
                        updateBinding.confirmPasswordText.setEnabled(false);
                        updateBinding.confirmPasswordText.setVisibility(View.GONE);
                    } else {
                        // 校验通过后清除新密码错误提示
                        updateBinding.passwordTextTip.setText("");
                        newPasswordCheck = true;
                        // 显示确认密码输入框
                        updateBinding.confirmPasswordText.setEnabled(true);
                        updateBinding.confirmPasswordText.setVisibility(View.VISIBLE);
                    }
                }
            }
        });

        // 确认新密码文本框输入后监听
        updateBinding.confirmPasswordText.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!update && newPasswordCheck) {  // 如果是修改密码操作，并且新密码校验全部通过
                    String confirmPassword = updateBinding.confirmPasswordText.getText().toString().trim();
                    String newPassword = updateBinding.passwordText.getText().toString().trim();
                    // 判断两次输入密码是否一致
                    if (newPassword.equals(confirmPassword)) {
                        updateBinding.confirmPasswordTextTip.setTextColor(ContextCompat.getColor(MainActivityUpdate.this, R.color.red));
                        updateBinding.confirmPasswordTextTip.setText("");
                        commit = true;  // 标记为可以提交修改
                    } else {
                        updateBinding.confirmPasswordTextTip.setTextColor(ContextCompat.getColor(MainActivityUpdate.this, R.color.red));
                        updateBinding.confirmPasswordTextTip.setText("与新密码不一致");
                        commit = false; // 标记为不允许提交修改
                    }
                }
            }
        });

        // 修改提交按钮
        updateBinding.submitBtn.setOnClickListener(view -> {
            if (update){    // 如果是修改账号操作
                if (newAccountCheck){ // 如果新账号校验通过
                    // 检查新账号是否和数据库中的账号重复
                    User user = mySQLiteOpenHelper.queryUserByAccount(updateBinding.accountText.getText().toString().trim());
                    if (user != null) {
                        updateBinding.accountTextTip.setTextColor(ContextCompat.getColor(MainActivityUpdate.this, R.color.red));
                        updateBinding.accountTextTip.setText("同名账号已存在");
                        return;
                    }
                    Map<String, Object> info = SharedPreferencesService.getUserInfo(this);
                    Integer userId = (Integer) info.get("userId");
                    String roleName = updateBinding.accountText.getText().toString().trim();
                    String password = (String) info.get("password");
                    boolean isSuccess = mySQLiteOpenHelper.updateUser(new User(userId, roleName, password));
                    if (isSuccess) {
                        // 更新本地缓存中的登录用户信息
                        SharedPreferencesService.updateUserInfo(this, roleName, password);
                        // 提示账号更改成功，跳转到个人界面，并结束当前界面
                        Toast.makeText(this, "账号更改成功", Toast.LENGTH_SHORT).show();
                        intent = new Intent(this, MainActivity2PageView.class);
                        intent.putExtra("return", "update");
                        startActivity(intent);
                        finish();
                    } else {
                        Toast.makeText(this, "账号更改失败", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(this, "与旧账号一致", Toast.LENGTH_SHORT).show();
                }
            } else {    // 如果是修改密码操作
                if (newAccountCheck && newPasswordCheck && commit) {  // 如果账号一致，新密码校验通过，并且可以提交修改
                    Map<String, Object> info = SharedPreferencesService.getUserInfo(this);
                    Integer userId = (Integer) info.get("userId");
                    String roleName = updateBinding.accountText.getText().toString().trim();
                    String password = updateBinding.passwordText.getText().toString().trim();
                    boolean isSuccess = mySQLiteOpenHelper.updateUser(new User(userId, roleName, password));
                    if (isSuccess) {
                        // 更新密码后删除本地缓存的用户信息
                        SharedPreferencesService.deleteUserInfo(this);
                        // 提示密码更改成功，跳转到登录界面，并结束当前界面
                        Toast.makeText(this, "密码更改成功", Toast.LENGTH_SHORT).show();
                        intent = new Intent(this, MainActivityLogin.class);
                        startActivity(intent);
                        finish();
                    } else {
                        Toast.makeText(this, "密码更改失败", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(this, "账号或密码不一致", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 返回图标监听
        updateBinding.updateTop.topReturn.setOnClickListener(view -> {
            finish();
        });
    }
}